package com.ss.mq.pattern.workqueue;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.ss.mq.util.RabbitUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 叁昇
 * @create 2020-12-12-15:44
 */
public class WorkQueueConsumer {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare("FinalWorkQueue", true, false, false, null);
        System.out.println("等待接收消息...");

        // 一次只接受一条消息
        channel.basicQos(1);

        DeliverCallback callback = (s, delivery) -> {
            String msg = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("收到: [ " + msg +" ]");

            // 遍历字符串中的字符, 每个点使进程暂停一秒
            for (int i = 0; i < msg.length(); i++) {
                if (msg.charAt(i)=='.') {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("消息处理完毕!");

            // 手动发送回执
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };

        CancelCallback cancel = s -> {};

        // autoAsk 设置为 false 时, 则需要手动确认发送回执
        channel.basicConsume("FinalWorkQueue", false, callback, cancel);
    }
}
